package com.pek.config;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson2.JSONObject;
import com.pek.Exception.TokenException;
import com.pek.control.entity.UserEntity;
import com.pek.control.service.IUserService;
import com.pek.control.util.RedisUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
public class Validate {
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IUserService userService;

    public UserEntity validateToken() throws TokenException {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request;
        try {
            request = sra.getRequest();
        } catch (NullPointerException ex) {
            throw new RuntimeException("Request 不能为空");
        }
        String token = request.getHeader("TOKEN");
//        如果TOKEN为空则抛出异常 / 停止运行此方法
        if (StringUtils.isEmpty(token)) {
            throw new TokenException("TOKEN 不能为空！");
        }
        if(!redisUtil.hasKey(token)){
            throw new TokenException("TOKEN 不存在！");
        }
        JSONObject object=(JSONObject) redisUtil.get(token);
        if(!getIp().equalsIgnoreCase(object.getString("ip"))){
            throw new TokenException("登录 IP 验证失败");
        }
        var user=userService.getUser(object.getString("user"),object.getString("pwd"));
        if(user==null){
            throw new TokenException("TOKEN 验证失败 ! 请尝试重新登录 !");
        }
        return user;
    }

    public static String getIp() {
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes == null) {
            return "unknown";
        }
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
